<template>
  <common-layout>
    <div class="login">
      <a-form v-if="!loginByApp" ref="formData" @submit="onSubmit" :form="form">
        <div
          id="QRCode"
          class="QRCode"
          style="float: right"
          @click="handleLoginType"
        ></div>
        <a-tabs class="tabs" @tabClick="tabsCallback" size="large">
          <a-tab-pane tab="密码登录" key="1">
            <a-alert
              type="error"
              :closable="true"
              v-if="error"
              :message="error"
              @close="onClose"
              showIcon
              style="margin-bottom: 24px"
            />
            <a-form-item>
              <a-input
                autocomplete="autocomplete"
                size="large"
                placeholder="请输入账户名"
                class="accessName"
                v-decorator="[
                  'name',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入账户名',
                        whitespace: true,
                      },
                    ],
                  },
                ]"
              >
                <!-- <a-icon slot="prefix" type="user" /> -->
                <medoIcon slot="prefix" iconClass="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input
                size="large"
                placeholder="请输入密码"
                autocomplete="autocomplete"
                type="password"
                v-decorator="[
                  'password',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入密码',
                        whitespace: true,
                      },
                    ],
                  },
                ]"
              >
                <!-- <a-icon slot="prefix" type="lock" /> -->
                <medoIcon slot="prefix" iconClass="lock" />
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane tab="短信登录" key="2">
            <a-form-item>
              <a-input
                size="large"
                placeholder="手机号码"
                :maxLength="11"
                v-decorator="[
                  'phone',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入手机号码',
                        whitespace: true,
                      },
                      {
                        pattern: /^1\d{10}$/,
                        message: '请输入正确的手机号码',
                        trigger: ['change', 'blur'],
                      },
                    ],
                  },
                ]"
              >
                <!-- <a-icon slot="prefix" type="mobile" /> -->
                <medoIcon slot="prefix" iconClass="phone" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-row :gutter="8" style="margin: 0 -4px">
                <a-col :span="16">
                  <a-input
                    size="large"
                    placeholder="验证码"
                    v-decorator="[
                      'code',
                      {
                        rules: [
                          { required: true, message: '请输入验证码' },
                          {
                            pattern: /^[0-9]*$/,
                            message: '验证码为数字',
                            trigger: ['change', 'blur'],
                          },
                          {
                            pattern: /^\d{6,}$/,
                            message: '验证码为6位',
                            trigger: ['change', 'blur'],
                          },
                        ],
                      },
                    ]"
                  >
                    <!-- <a-icon slot="prefix" type="mail" /> -->
                  </a-input>
                </a-col>
                <a-col :span="8" style="padding-left: 4px">
                  <a-button
                    style="width: 100%"
                    class="captcha-button"
                    size="large"
                    :disabled="disabled"
                    @click="getCode"
                  >
                    {{ timerHtml }}
                  </a-button>
                </a-col>
              </a-row>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>

        <a-form-item>
          <a-button
            :loading="logging"
            style="width: 100%; margin-top: 24px"
            size="large"
            htmlType="submit"
            type="primary"
            class="submitPrimary"
          >
            登录
          </a-button>
        </a-form-item>
        <div style="color: #8f95a5">
          <a @click="handerLoginByWechat('wechat', [], 0)">
            <!-- <a-icon
              class="icon"
              type="wechat"
              @click="handerLoginByWechat('wechat', [], 0)"
            /> -->
            <medoIcon
              class="icon"
              iconClass="wechat"
              style="margin-right: 5px"
            />
            <span>微信登录</span>
          </a>
          <a v-show="forgetPwd" class="forgetPwd" style="float: right">
            忘记密码?
          </a>
        </div>
      </a-form>

      <a-form v-else>
        <div
          id="PCLogin"
          class="PCLogin"
          style="float: right"
          @click="handleLoginType"
        ></div>
        <a-tabs size="large">
          <a-tab-pane tab="米度云登录" key="1" style="text-align: center">
            <a-form-item>
              <vue-qr :text="text" :margin="0"></vue-qr>
              <img
                @click="refreshQR"
                v-if="loseImgShow"
                class="loseimg"
                src="~@/assets/img/loseImage.png"
              />
            </a-form-item>
            请使用米度云APP扫描二维码登录
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </div>
    <table-edit ref="edit"></table-edit>
  </common-layout>
</template>

<script>
  const timeList = ['早上好', '上午好', '中午好', '下午好', '晚上好']

  import CommonLayout from '@/layouts/CommonLayout'

  import {
    signIn,
    // getRoutesConfig,
    getUserByToken,
    smsLogin,
  } from '@/services/login/auth'
  import TableEdit from './components/TableEdit'
  import { setAuthorization } from '@/utils/request'
  import { logout } from '@/services/login/auth'
  import { loadRoutes } from '@/utils/routerUtil'
  import { hasPermission } from '@/utils/authority-utils'
  import { queryAllPermissionInService } from '@/services/permission/systemPermission'
  import { sendSmsCode } from '@/services/access/user'
  import { mapMutations } from 'vuex'
  import vueQr from 'vue-qr'

  export default {
    name: 'Login',
    components: { CommonLayout, TableEdit, vueQr },
    inject: ['reload'],
    data() {
      return {
        loginByApp: false,
        logging: false,
        text: '用户权限管理平台米度云扫描登录正在开发中。。。',
        forgetPwd: true,
        loseImgShow: false,
        refreshInterval: undefined,
        timer: 0,
        error: '',
        form: this.$form.createForm(this),
        paneKey: 1,
        timerHtml: '获取验证码',
        disabled: false,
      }
    },
    computed: {
      systemName() {
        return this.$store.state.setting.systemName
      },
    },

    methods: {
      ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
      onSubmit(e) {
        e.preventDefault()
        if (this.paneKey == 1) {
          this.form.validateFields(['name', 'password'], (err) => {
            if (!err) {
              this.logging = true
              const account = this.form.getFieldValue('name')
              const password = this.form.getFieldValue('password')
              signIn({ account, password })
                .then(this.afterLogin)
                .catch((res) => {
                  console.log('err------', res)
                  this.logging = false
                })
            }
          })
        } else {
          this.form.validateFields(['phone', 'code'], (err) => {
            if (!err) {
              this.logging = true
              const phone = this.form.getFieldValue('phone')
              const code = this.form.getFieldValue('code')
              smsLogin({ phone, code })
                .then(this.afterLogin)
                .catch((res) => {
                  console.log('err------', res)
                  this.logging = false
                })
            }
          })
        }
      },
      afterLogin(res) {
        if (res.code != 0) {
          return
        }
        this.logging = false
        let { data } = res
        //设置请求 token
        setAuthorization({
          token: data,
          expireAt: new Date(new Date().getTime() + 30 * 60 * 1000),
        })
        getUserByToken().then((res) => {
          this.setUser(res.data)
          localStorage.setItem('currentUser', JSON.stringify(res.data))
          //获取当前用户所有权限
          queryAllPermissionInService({
            companyID: res.data.companyID,
          }).then((result) => {
            let permissions =
              result.data &&
              result.data.map((item) => {
                return item.serviceName + ':' + item.permissionToken
              })
            this.setPermissions(permissions)
            console.log(permissions, 'permissionspermissionspermissions')
            if (hasPermission('user:DescribeUserDashboard', permissions)) {
              // 获取路由配置
              // getRoutesConfig().then((result) => {
              //   const routesConfig = result.data
              //   console.log(result.data, 'result.data')

              // })
              loadRoutes([])
              this.$router.push('/')
              this.$message.success(this.timeFix() + ',欢迎回来~', 3)
            } else {
              this.$message.error('当前用户未授权登录平台权限，请联系管理员！')
              logout()
            }
          })
        })
      },
      handleLoginType() {
        this.loginByApp = !this.loginByApp
        if (this.loginByApp) {
          this.refreshQR()
        } else {
          this.refreshInterval && clearInterval(this.refreshInterval)
          this.loseImgShow = false
        }
      },
      handerLoginByWechat(operateType = 'wechat', rowData = [], isFooter = 1) {
        this.$refs.edit.showModal(operateType, rowData, isFooter)
      },
      tabsCallback(key) {
        this.forgetPwd = key == 1 ? true : false
        this.paneKey = key
      },
      refreshQR() {
        this.timer = 0
        this.loseImgShow = false
        this.text = '用户权限管理平台米度云扫描登录正在开发中。。。'

        this.refreshInterval = setInterval(() => {
          this.text = '用户权限管理平台米度云扫描登录正在开发中。。。'
          if (this.timer == 60) {
            this.refreshInterval && clearInterval(this.refreshInterval)
            this.loseImgShow = true
          }
          this.timer++
        }, 10000)
      },
      timeFix() {
        const time = new Date()
        const hour = time.getHours()
        return hour < 9
          ? timeList[0]
          : hour <= 11
          ? timeList[1]
          : hour <= 13
          ? timeList[2]
          : hour <= 20
          ? timeList[3]
          : timeList[4]
      },
      onClose() {
        this.error = false
      },
      getCode() {
        /* if (!this.form.getFieldValue('phone')) {
          this.$message.error('请输入手机号码')
          return
        } */
        this.form.validateFields(['phone'], (err, values) => {
          console.log('err----------', err)
          console.log('values----------', values)
          if (values.phone) {
            sendSmsCode({
              phone: this.form.getFieldValue('phone'),
            }).then((res) => {
              this.setTimerHtml()
              this.$message.success(res.data || '验证码已发送')
            })
          }
        })
      },
      //发送验证码
      setTimerHtml() {
        let timer_num = 60
        this.timerHtml = '重发验证(60)'
        this.disabled = true
        this.timeClock = setInterval(() => {
          timer_num--
          this.timerHtml = '重发验证(' + timer_num + ')'
          if (timer_num == 0) {
            clearInterval(this.timeClock)
            this.timerHtml = '获取验证码'
            this.disabled = false
          }
        }, 1000)
      },
    },
  }
</script>

<style lang="less" scoped>
  .common-layout {
    background-color: #f3f6fb;
    /deep/ .ant-tabs-bar {
      border-bottom: 1px solid lightgrey;
    }
    .login {
      position: absolute;
      right: 12.5%;
      width: 380px;
      padding: 30px;
      margin: 0 auto;
      // background: @layout-body-background;
      background: #fff;
      border-radius: 4px;
      .tabs {
        padding: 0 5px;
        /deep/ .ant-tabs-nav .ant-tabs-tab-active {
          font-weight: 600;
          color: #212224;
        }
        /deep/ .ant-tabs-ink-bar {
          background-color: #01d3b8;
        }
        /deep/ .ant-tabs-nav .ant-tabs-tab:hover {
          color: #01d3b8;
        }
      }
      .PCLogin {
        position: absolute;
        top: 0px;
        right: 0px;
        display: inline-block;
        width: 48px;
        height: 48px;
        margin-bottom: 4px;
        cursor: pointer;
        background: url('~@/assets/img/PCLogin.png') no-repeat;
        background-size: 48px 48px;
      }

      .QRCode {
        position: absolute;
        top: 0px;
        right: 0px;
        display: inline-block;
        width: 48px;
        height: 48px;
        margin-bottom: 4px;
        cursor: pointer;
        background: url('~@/assets/img/QRcode2.png') no-repeat;
        background-size: 48px 48px;
      }
      .loseimg {
        position: absolute;
        right: -2px;
        margin-top: -2px;
        cursor: pointer;
      }
      .captcha-button {
        font-size: 12px;
        color: #fff;
        background-color: #01d3b8;
      }
      @media screen and (max-width: 576px) {
        position: relative;
        right: 0;
        width: 95%;
        margin: 0 auto;
      }
      @media screen and (max-width: 320px) {
        button {
          font-size: 14px;
        }
      }
      .icon {
        margin-left: 6px;
        font-size: 24px;
        color: @text-color-second;
        vertical-align: middle;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: @primary-color;
        }
      }
      .submitPrimary {
        background-color: #01d3b8;
        border: none;
        border-radius: 2px;
      }

      /deep/ .ant-input-lg {
        background-color: #f1f4f5;
        border-color: transparent;
      }
      /deep/.ant-input-affix-wrapper {
        .ant-input {
          font-weight: 500;
          color: #212224;
          &:focus {
            border: 1px solid #01d3b8;
            // box-shadow: none;
            outline: none;
          }
        }
      }
    }
  }
  .forgetPwd {
    text-decoration: underline;
  }
</style>
